<template>
  <view>
    <loading :showLoaded.sync="showLoaded"></loading>
    <tabBar ref="tabBarRef" :nowPages.sync="nowPages" :tsActId='tsActId'></tabBar>
    <onlineService></onlineService>
    <view class="page_box" :class="showLoaded?'hiddenHome':'showHome'">
      <custom-nav-bar :nav-bar-info="navBarInfo" />
      <scroll-view id="homePageScrollView" class="scrollarea" :class="isIpx?'scrollisIpx':''" @scroll="handleScrollTop"
        :scroll-with-animation="true" :scroll-top="scrollTop" :scroll-y="utoolsPosition" type="list">
        <view style="position: relative" v-if="utoolsShow">
          <utools-parse id="utools-parse" page="home" @triggerComponent="onTriggerComponent" @utoolsEvents="onUtoolsEvents" :utools-data="utoolsData"
            @onAddCart="onAddCart" @joinVip="onJoinVip"></utools-parse>
          <view style="width:100%;height:100rpx;"></view>
        </view>
        <view class="down-arrow" :style="{bottom: bottom}" v-if="downArrowShow" @click="onScrollTap">
          <image class="down-arrow-img"
            src="https://morefun-active.oss-cn-beijing.aliyuncs.com/2024macallan_wechat/ChevronDown.png" />
        </view>
      </scroll-view>
    </view>
    <view v-if="!!partPaymentArr && partPaymentArr.length > 0 " class="paty-payment" :style="{top : positionTop}"
      :class=" !isIpx ? 'paty-payment-ipx':''" @click="toOrder">
      <text>您有待付款的订单，请尽快完成付款</text>
      <image src='https://100000063-1252208446.file.myqcloud.com/images/arrowPay.png' mode="widthFix"></image>
    </view>
    <welcome ref="welcomeRef" class="show-welcome-box" :tsActId='tsActId' @handleLoad='handleLoad'>
    </welcome>
    <taskDialog @doHelp='doHelp' :taskStatus='taskStatus' @closeDialog='closeDialog' v-if="showTaskHelp">
    </taskDialog>
    <register-widget ref="registerWidgetRef" location="home" @finish="onRegisterWidgetFinish" :tsActId="tsActId"
      @registerSuccess='registerSuccess' />
    <!-- 加购提示、抽签购中签底部横幅 -->
    <cart-toast v-if="showCartMsg" :cartMessage='cartMessage' :cartStatus='cartStatus' :path="cartPath"></cart-toast>
    <block v-if="tsTopBannerJson && tsTopBannerShow">
      <view class="ts_activity_banner" :style="{top: positionTop, opacity: tsTopBannerShow ? 1 : 0}">
        <utools-parse id="utools-parse-ts" page="home" @triggerComponent="onTriggerComponent"
          :utools-data="tsTopBannerJson" @onAddCart="onAddCart" @joinVip="onJoinVip"></utools-parse>
      </view>
    </block>
    <!-- 特邀活动 -->
    <block v-if="speciallyInviteLists.length && speciallyInviteShow">
      <speciallyInviteDialog :jsonData="speciallyInviteLists"></speciallyInviteDialog>
    </block>
		<!-- 弱提示 弹窗 -->
		<toast-popup ref="toastPopup" @onToastPopupClick="onToastPopupClick"></toast-popup>
		<!-- 爱奇艺App返回按钮 -->
		<backApp v-if="backIqiyiPdp"></backApp>
  </view>
</template>

<script>
  let observer = null;
  // import Vue from 'vue';
  import api from '@/api/api';
  import tip from '@/utils/tip';
  import TabBar from '@/components/common/tabbar';
  import NavBar from '@/components/common/navbar';
  import onlineService from '@/components/common/onlineService';
  import TaskDialog from './taskHelpDialog.vue';
  import loading from '@/components/common/loading';
  import Welcome from './welcome.vue';
  import registerWidget from "@/components/register/register-widget.vue";
  import CartToast from '@/components/common/cartToast';
  import speciallyInviteDialog from "./speciallyInviteDialog.vue";
	import backApp from '@/components/common/backApp';
  import {
    SEL_CLASS_CODE,
    SEL_ACTIVE_CODE,
    SYSTEM_INFO,
    USER_INFO,
    CUSTOMER_INFO,
    CUSTOMER_HOTFIX,
    CART_KEY,
    MERCHANT_INFO,
    USER_SPECICAL_INFO
  } from '@/utils/constant';
  export default {
    components: {
      navBar: NavBar,
      onlineService: onlineService,
      tabBar: TabBar,
      taskDialog: TaskDialog,
      loading: loading,
      welcome: Welcome,
      registerWidget,
      CartToast,
      speciallyInviteDialog,
			backApp
    },
    data() {
      return {
        tabbarTimeout: true,
        customTabbar: 1,
        // 组件所需的参数
        navbarData: {
          showCapsule: 0, //是否显示左上角图标   1表示显示    0表示不显示
          title: '我的主页', //导航栏 中间的标题
          newLogo: uni.getStorageInfoSync('storeLogo'),
          isTopFixed: true
        },
        isShowCustomNavBar: true,
        isIpx: false,
        nowPages: '',
        backgroundImage: 'https://www.cosstores.cn/img/dm/pageup/190318/sale-mob.jpg',
        cmsConfigData: [],
        identifier: 'home',
        preview: false,
        content: '',
        isSwiperscaleAnimation: true, // 轮播缩放效果
        showTaskHelp: false, // 好友助力弹窗
        taskStatus: 3,
        taskParams: {},
        sceneType: '',
        showLoaded: true,
        partPaymentArr: [],
        toPay: false,
        submitOrderId: '',
        positionTop: '87px',
        tsActId: '',
        finish: false,
        showRegister: 0,
        timeObj: {},
        goodsId: 0, //热区里面传过来的商品id
        registerType: '', //cart 点击加购按钮，nonMember点击入会按钮赋的值
        swiperCircle: false, //搭建出来的首页swiper是否轮播，在首页18岁弹窗结束后开启自动轮播
        cartMessage: '',
        cartStatus: false,
        showCartMsg: false,

        navBarInfo: {
          page: "index",
          logo: "https://100000063-1252208446.file.myqcloud.com/images/macallan-remvp/white-logo.png",
          leftIcon: "https://100000063-1252208446.file.myqcloud.com/images/macallan-remvp/search.png",
          backgroundColor: 'transparent',
        },
        scrollTop: 0,
        utoolsData: {},
        utoolsShow: false,
        utoolsClassGoodsLists: null,
        systemInfo: {},
        downArrowShow: true,
        utoolsPosition: true,
        utoolsShopLists: [],
        campaignTargetSaleId: null,
        campaignTargetSaleData: null,
        tsTopBannerJson: null,
        tsTopBannerShow: false,
        rewriteTabCurrIndex: 0, //  utools组件内容部 tab切换的动态index
        userOrderLists: [], //  用户订单列表，给utools 抽签购组件使用
        ballotGoodsLists: [], //首页抽签购商品列表
        utoolsMetaData: null, //  utools元数据存储
        shareImage: '',   //页面分享图片
        shareTitle: '',   //页面分享标题
        pagePath: '',     //页面分享路径
        pageQuery: '',    //页面分享参数
        cartPath: "",
        speciallyInviteLists: [],   //  特邀活动json数据
        speciallyInviteShow: false,
        scrollTimer: null,
        balloutReload: false,
				backIqiyiPdp: false,
      }
    },
    computed: {
      getName() {
        return this.$store.state.storeName;
      }
    },
    async onLoad(option) {
      try {
        let that = this;
				
				if(option?.utm_source == "Iqiyi" || option?.utm_source == "iqiyi"){
					this.backIqiyiPdp = true;
				}
				
        this.systemInfo = uni.getSystemInfoSync();
        this.tsActId = option && option.tsActId;
        await this.$onLaunched;
        setTimeout(async () => {
          let customerInfo = uni.getStorageSync(CUSTOMER_INFO)
          if (!!customerInfo) {
            that.showRegister = 1
          } else {
            that.showRegister = 2
          }
        }, 500);
        this.statusBarHeight = this.systemInfo.statusBarHeight;
        let rect = uni.getMenuButtonBoundingClientRect ? uni.getMenuButtonBoundingClientRect() : null; //胶囊按钮位置信息
        uni.getMenuButtonBoundingClientRect();
        let navBarHeight = (function() {
          //导航栏高度
          let gap = rect.top - that.systemInfo.statusBarHeight; //动态计算每台手机状态栏到胶囊按钮间距
          return 2 * gap + rect.height;
        })();

        this.titleBarHeight = navBarHeight;
        this.positionTop = navBarHeight + this.systemInfo.statusBarHeight + 'px';
        that.customTabbar = this.$programSetting.customTabbar ? 1 : 0
        let pages = getCurrentPages();
        var currPage = pages[pages.length - 1];
        this.nowPages = currPage.route;
        let merchantInfo = uni.getStorageSync(MERCHANT_INFO);
        that.merchantId = merchantInfo.cloudMerchantId;
        that.getPageShareData();
        let interval = setInterval(() => {
          if (getApp().globalData.flag) {
            clearInterval(interval); // 清理定时器
          }
        }, 50);

        if (this.$store.state.ageModalChecked) {
          setTimeout(() => {
            this.swiperAutoPlay()
          }, 5000)

        } else {
          let interval2 = setInterval(() => {
            if (this.$store.state.ageModalChecked) {
              this.swiperAutoPlay()
              clearInterval(interval2); // 清理定时器
            }
          }, 100);
        }
      } catch (e) {
        console.log("#####  home-onLoad-error", e)
      }
    },
    async onShow() {
      try {
        await this.$onLaunched;
        let that = this;
        if (uni.getStorageSync('buyerPartPayment')) {
          this.getMyOrder()
        }
        if (!!this.submitOrderId) {
          that.showLoaded = true
          this.getOrderInfo()
        }
        setTimeout(() => {
          that.tabbarTimeout = true;
        }, 400)
        that.$commonFunction.getCartList().then((res) => {}).catch((err) => {});
        let systemInfo = uni.getStorageSync(SYSTEM_INFO);
        this.isIpx = getApp().globalData.isIpx;
        uni.setStorageSync(SEL_CLASS_CODE, '');
        uni.setStorageSync(SEL_ACTIVE_CODE, -1);
        // this.$refs.cmsPage.updateUserLoginState();
        let pages = getCurrentPages();
        let currentPages = pages[pages.length - 1]
        let option = currentPages.options;
        let sceneCode = uni.getStorageSync('sceneCode')
        this.sceneType = option && option.type

        this.taskParams = (option && option.params) ? JSON.parse(decodeURIComponent(option.params)) : {};
        if (option && (sceneCode == '1007' || sceneCode == '1008') && this.finish) {
          if (option.type == 'taskHelp') {
            this.taskInviteHelp()
          }
        }
        const _arr = ['1089', '1007', '1008'];
        if (_arr.includes(sceneCode) && this.finish && this.sceneType !== 'taskHelp' && !!uni.getStorageSync(
            'firstEnter')) {
          //开屏与好友助力弹窗的冲突
          this.openWelcomeDialog()
        }
        getApp().cl_tracker.track('mini_program_view', {
          path: '/pages/home/home',
          pageName: '首页',
        })
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
        if (customerInfo) {
          await this.handleAjaxAll(customerInfo);
        }
        //  utools数据拉取
        await this.getHomeUtoolsData(option);
        //  首页页面滚动监听
        this.trackHomePageView();
        // 首页TS活动吸顶横幅
        this.getTsTopBanner();
        // 首页抽签购子组件刷新
        this.checkHasBallout();

        //  抽签购底部横幅
        this.getBalloutText();
      } catch (e) {
        console.log("##### home-onShow-error:", e)
      }
    },
    //点击首页tabber埋点
    onTabItemTap(e) {
      let text = e.text
      let clTrackPrams = {
        'c_tab': "首页",
        'c_link_pagename': e.text,
        'c_link_path': e.pagePath
      }
      getApp().commonClTrack('c_ebmp_click_tabbar', clTrackPrams)
    },
    onHide() {
      this.$store.commit('changeWelcomeDialogStatus', false)
      if (observer) {
        observer.disconnect()
      }
    },
    onUnload(options) {
      // 页面关闭后销毁实例
      if (observer) {
        observer.disconnect()
      }
      // this.interstitialAd.destroy()
    },
    methods: {
			/**
			 * 展示弱提示
			 * @param {Object} msg 文案
			 */
			handleShowTextToast(msg){
				try{
					this.$refs.toastPopup.showToast(msg);
				}catch(e){}
			},
			/**
			 * 若提示按钮点击回调
			 * @param {Object} data.type 类型：confirm确定，cancel取消
			 * @param {Object} data.callBackData 呼气弹窗时传入的数据
			 */
			onToastPopupClick(data){

			},
      // 多个接口同时请求
      async handleAjaxAll(customerInfo){
        //  特邀活动弹窗信息查询
        this.getActivityList(customerInfo);
        let merchantInfo = uni.getStorageSync(MERCHANT_INFO) || getApp().globalData.merchantInfo;
        Promise.all([this.handleGetUserTsData(customerInfo, merchantInfo), this.getOrder(customerInfo, merchantInfo)])
          .then(results => {
            return true;
          })
          .catch(error => {
            return false;
          });
      },
      //  特邀活动信息查询
      async getActivityList(customerInfo) {
        try{
          this.speciallyInviteLists = [];
          const res = await api.getActivityList({
            header: {
              jwt: customerInfo.jwt
            }
          });
          if (res.code === 1000 && res.data && res.data.length) {
            for(let i=0;i<res.data.length;i++){
              if(res.data[i].activityType == "Special_Activity"){
                const _jsonData = await this.getActivityAlertImg(res.data[i].activityId)
                this.speciallyInviteLists.push({
                  ...res.data[i],
                  jsonData: _jsonData
                })
              }
            }
          }
        }catch(e){
          this.speciallyInviteShow = false;
        }
      },
      //  查询特邀活动信息弹窗
      async getActivityAlertImg(activityId){
        try{
          const res = await api.getDataInfoByIdAndType({
            method: 'GET',
            type: "activity_window_value",
            activityId: activityId
          });
          if(res && res.success && res.data && res.data.jsonData){
            return JSON.parse(res.data.jsonData);
          }
          return null;
        }catch(e){}
        return null;
      },
      /**
       * 查询分享数据
       * @param {Object} option
       */
      async getPageShareData() {
        try {
          const res = await this.$commonFunction.getShareinfoByCode('home');
          this.shareImage = res.shareImage;
          this.shareTitle = res.shareTitle;
          this.pagePath = res.pagePath; //  当前页面路由
          this.pageQuery = res.pageQuery; //  当前页面url参数
        } catch (e) {}
      },
      //  判断是否需要调用抽签购子组件刷新
      async checkHasBallout(){
        try{
          const that = this;
          let _ballot = false;
          this.utoolsData.children.forEach(item => {
            if (item.boxType == "draw" && item.type == "box") _ballot = true;
          });
          if(_ballot && this.balloutReload && this.ballotGoodsLists.length){
            // ############   抽签购活动组件需要 重新加载  ############
            for(let i=0;i<this.ballotGoodsLists.length;i++){
              let domRef = that.selectComponent(`#utools-parse >>> #${this.ballotGoodsLists[i].domId}`)
              if(domRef && domRef.balloutInit) domRef.balloutInit();
            }
          }
        }catch(e){}
      },
      //  抽签购子组件 调用父组件方法
      async setTopBar(item){
        if(item && !this.ballotGoodsLists.find(ite=>item.domId == ite.domId)){
          this.ballotGoodsLists.push(item);
        }
        this.balloutReload = true;
      	// this.timeouter && clearTimeout(this.timeouter),this.timeouter=null;
      	// this.timeouter = setTimeout(()=>{
      		//  首页抽签购中签 底部横幅
      		// this.getBalloutText();
      	// },1000)
      },
      //  查询用户订单数据给 抽签购使用
      async getOrder(customerInfo, merchantInfo){
        try{
          const parmas = {
            customer_id: customerInfo.customerId,
            merchant_id: merchantInfo.cloudMerchantId,
            page_no: 1,
            page_size: 100,
            store_id: merchantInfo.cloudMerchantStoreId
          };
          let json = await api.getMyOrderList({
            header: {
              jwt: customerInfo.jwt
            },
            query: parmas
          });
          this.userOrderLists = json?.data?.data?.content || [];
          return true;
        }catch(e){
          this.userOrderLists = [];
          return false;
        }
      },
      //  查询用户ts活动信息
      async handleGetUserTsData(customerInfo, merchantInfo) {
        let memberDetails = uni.getStorageSync("memberDetails");
        if(!memberDetails) return false;
        const result = await api.getTsByUser({
          header: {
            jwt: customerInfo.jwt,
          },
          method: "GET",
          query: {
            store_id: merchantInfo.cloudMerchantStoreId,
            group_id: customerInfo.groupId,
            member_level_id: memberDetails.memberLevelId,
          },
        });

        if (result.code == 1000 && result.data) {
          this.campaignTargetSaleId = result.data.campaignTargetSaleId;
          this.campaignTargetSaleData = result.data;
          return true;
        } else {
          this.campaignTargetSaleId = null;
          this.campaignTargetSaleData = null;
          return false;
        }
      },
      //  组装处理首页 轮播ts活动展示问题
      async buildTsDataHomeSwiper(jsonData) {
        try {
          const _tsid = this.campaignTargetSaleId;
          // 首页轮播TS内容处理
          let homeSwiper = null;
          jsonData.children.forEach(element => {
            if (element.label1 === '首屏swiper') homeSwiper = element;
          })

          if (homeSwiper && homeSwiper.children) {
            const _filterArr = [];
            for (let i = 0; i < homeSwiper.children.length; i++) {
              const item = homeSwiper.children[i];
              const _TSbox = item.children.find(els=>els.type === 'box' && els.boxType === 'TS');
              if (_TSbox) {
                if (_tsid && _TSbox.label1 == String(_tsid)) {
                  _filterArr.push(item);
                } else {
                  continue;
                }
              } else {
                _filterArr.push(item);
              }
            }
            if (_filterArr.length) {
              jsonData.children.forEach(element => {
                if (element.label1 === '首屏swiper') {
                  element.children = _filterArr;
                }
              })
            }
          }

          // 首页TS模块
          const _jsonChild = JSON.parse(JSON.stringify(jsonData.children));
          let _filterArr2 = [];
          for (let i = 0; i < _jsonChild.length; i++) {
            const item = _jsonChild[i];
            if (item.type === 'box' && item.boxType === 'TS') {
              if (_tsid && item.label1 == String(_tsid)) {
                _filterArr2.push(item);
              } else {
                continue;
              }
            } else {
              _filterArr2.push(item);
            }
          }
          jsonData.children = _filterArr2;
        } catch (e) {}
        return jsonData;
      },
      //  筛选utools json中的商品列表对象
      async filterUtoolsShopLists(data, key, value) {
        try {
          if (data && data[key] && data[key] === value) {
            this.utoolsShopLists.push(data)
            return true;
          }
          if (data && data.children && data.children.length) {
            for (let i = 0; i < data.children.length; i++) {
              if (data.children[i]) {
                await this.filterUtoolsShopLists(data.children[i], key, value);
              }
            }
          }
          return null;
        } catch (e) {}
      },
      //  线上精选神策埋点
      async trackProductBannerExpo(id) {
        try {
          this.utoolsShopLists = [];
          const uData = this.utoolsData.children.filter(it => it.id == id)[0];
          if (uData && uData.type) {
            //  首页神策埋点 商品列表筛选
            await this.filterUtoolsShopLists(uData, 'type', 'commodityList');
            const datas = this.utoolsShopLists[this.rewriteTabCurrIndex] || null;
            if (datas && datas.children && datas.children.length && datas.trackingParams) {
              let _trackData = JSON.parse(datas.trackingParams);
              if (_trackData.name && _trackData.data) {
                let product_sku_list = [];
                let product_name_list = [];
                datas.children.forEach(item => {
                  let goods = this.utoolsClassGoodsLists.filter(it => it.itemId == item.itemId)[0];
                  if (goods) {
                    if (goods.skuCodes && goods.skuCodes[0]) product_sku_list.push(goods.skuCodes[0]);
                    if (goods.itemName) product_name_list.push(goods.itemName);
                  }
                })
                if (product_sku_list.length && product_name_list.length) {
                  _trackData.data.product_sku_list = product_sku_list;
                  _trackData.data.product_name_list = product_name_list;
                  this.$commonSensors.lithaTrack.cTrack(_trackData.name, _trackData.data);
                } else {
                  // 商品列表product_sku_list或product_name_list为空，不触发埋点
                }
              } else {
                // 商品列表暂未配置trackingParams的name或data不存在，不触发埋点
              }
            } else {
              // 商品列表暂未配置trackingParams，不触发埋点
            }
          }
        } catch (e) {}
      },
      // 首页浏览 神策埋点
      trackHomePageView() {
        const that = this;
        setTimeout(() => {
          observer = uni.createIntersectionObserver(that, {
            observeAll: true,
            thresholds: [0.5]
          });
          observer.relativeToViewport({
            bottom: 50
          }).observe('#utools-parse >>> .se_track', (res) => {
            if (res.intersectionRatio > 0.5 && !!res.dataset.name) {
              that.$commonSensors.homePageEvent('HomePageView', {
                'module_name': res.dataset.name
              });
              if (res.dataset.label1 && res.dataset.label1 === "hasShopLists") {
                return that.trackProductBannerExpo(res.id);
              }
              if (res.dataset.track) {
                that.$commonUtoolsTrack.onTriggerComponent({
                  detail: {
                    data: {
                      trackData: res.dataset.track
                    }
                  }
                });
              }
            }
          })
        }, 1600)
      },
      swiperAutoPlay() {
        const _event = getApp().globalData.event;
        if (_event) _event.emit('swiperAutoPlay');
      },
      getNavBar() {
        // 获取系统信息
        const systemInfo = wx.getSystemInfoSync();
        // 胶囊按钮位置信息
        const rect = wx.getMenuButtonBoundingClientRect();
        let navBarHeight = (function() {
          //导航栏高度
          let gap = rect.top - systemInfo.statusBarHeight; //动态计算每台手机状态栏到胶囊按钮间距
          return 2 * gap + rect.height;
        })();
        getApp().globalData.navBarHeight = navBarHeight + systemInfo.statusBarHeight
      },
      //  utools数据格式化
      async getHomeJson(utoolsData) {
        if (!utoolsData) return false;
        let that = this;
        let jsonData = typeof(utoolsData) === "object" ? JSON.parse(JSON.stringify(utoolsData)) : JSON.parse(utoolsData);
        let dealData;
        let customerInfo = wx.getStorageSync('customerInfo') || getApp().globalData.customerInfo;
        if (!!customerInfo) {
          dealData = this.deleteObjectWithCondition(jsonData, 'boxType', 'nonMember');
        } else {
          dealData = this.deleteObjectWithCondition(jsonData, 'boxType', 'member');
        }
        //  剔除为null的数据
        dealData.children = dealData.children.filter(items => items);

        //  TS活动数据处理
        const dealData2 = await this.buildTsDataHomeSwiper(dealData);
        this.utoolsData = dealData2;
        this.utoolsShow = true;
        //下面是有数埋点
        if (this.utoolsClassGoodsLists?.length > 0) {
          let merchantInfo = wx.getStorageSync('merchantInfo')
          const _openOuterItemId = wx.getStorageSync('openOuterItemId');
          const _youshuOpencc = wx.getStorageSync('youshuOpencc');
          for (let i = 0; i < this.utoolsClassGoodsLists.length; i++) {
            if (this.utoolsClassGoodsLists[i].skuCodes !== undefined) {
              that.srTrackExposeSkuComponent(this.utoolsClassGoodsLists[i], _youshuOpencc, _openOuterItemId, merchantInfo.cloudMerchantId)
            }
          }
        }
        return true;
      },
      /**
       * 腾讯有数商品曝光埋点
       * @param {Object} item
       * @param {Object} _youshuOpencc
       * @param {Object} _openOuterItemId
       */
      srTrackExposeSkuComponent(item, _youshuOpencc, _openOuterItemId, cloudMerchantId) {
        try {
          this.$sr.track('expose_sku_component', {
            sku: {
              sku_id: item.skuCodes[0].toString(),
              sku_name: item.itemName // 若商品无sku_name时，可传spu_name信息
            },
            spu: {
              spu_id: !!_openOuterItemId ? item.outerItemId : !!_youshuOpencc ? item.frontCode.toString() : item
                .itemCode.toString(),
              spu_name: !!_youshuOpencc ? item.itemName + item.valueName : item
                .itemName // 若商品无spu_name时，可传sku_name信息
            },
            sku_category: [{
              sku_cat_id: item.categoryId.toString(),
              sku_cat_name: '全部商品',
              sku_parent_cat_id: 'null' // 若已是顶级类目，传"null"
            }],
            shipping_shop: {
              shipping_shop_id: cloudMerchantId.toString(), // 到家类型对接智慧零售入口必传
              shipping_shop_name: "THE MACALLAN EBOUTIQUE麦卡伦" // 到家类型对接智慧零售入口必传
            },
            sale: {
              original_price: parseFloat(item.price), // 对接智慧零售入口必传
              current_price: parseFloat(item.price) // 对接智慧零售入口必传
            },
            primary_image_url: item.majorUrl
          });
        } catch (e) {

        }
      },
      toParseRegisterSuccess() {
        // this.getHomeJson()
      },
      //根据条件删掉属性所在的对象
      deleteObjectWithCondition(obj, conditionType, conditionValue) {
        for (let key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (conditionType === 'boxType' && key === 'boxType' && obj[key] === conditionValue) {
              return null; // 返回 null 表示找到并删除了该对象
            } else if (conditionType === 'type' && key === 'type' && (obj[key] === 'hotSpace' || obj[
                key] === 'img') && obj['label1'] === conditionValue) {
              return null; // 返回 null 表示找到并删除了该对象
            } else if (typeof obj[key] === 'object' && obj[key] !== null) {
              // 如果当前值是对象，则递归查找
              var result = this.deleteObjectWithCondition(obj[key], conditionType, conditionValue);
              if (result === null) {
                delete obj[key]; // 删除包含匹配属性的对象
              }
            }
          }
        }
        return obj; // 返回删除任何对象的原始对象
      },
      pxToRpx(toTop) {
        const windowWidth = this.systemInfo.screenWidth; // 屏幕宽度（px）
        // 将滚动距离从px转换为rpx
        return (toTop * 750) / windowWidth;
      },
      rpxToPx(rpx) {
        return rpx * this.systemInfo.screenWidth / 750;
      },
      onScrollTap(event) {
        // return
        let tabBarRpx = getApp().globalData.isIpx ? 150 : 120
        let toPx = this.rpxToPx(tabBarRpx)
        //点击首屏是wiper的下箭头滚动的距离
        setTimeout(() => {
          this.scrollTop = this.systemInfo.screenHeight - getApp().globalData.navBarHeight - toPx + 2
        }, 300)
      },
      //商品和购物车有数埋点2
      onTriggerComponent(e) {
        try {
					const {type, msg} = e.detail.data;
					if(type === 'showToast' && msg){
						this.handleShowTextToast(msg);
					}else{
						this.$commonUtoolsTrack.onTriggerComponent(e);
					}
        } catch (e) {
          console.log("home-onTriggerComponent-error:", e)
        }
      },
      //  utools组件 事件回调
      onUtoolsEvents(e){
        const { detail: {data: {type, data} } } = e;
        if(type == 'rewriteTabCurrIndex'){
          //  tab切换的当前index,用于神策商品曝光埋点
          this.rewriteTabCurrIndex = data.currIndex || 0;
        }
      },
      // 商品加入购物车
      async addCart() {
        try {
          let merchantInfo = uni.getStorageSync('merchantInfo');
          let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
          let userInfo = uni.getStorageSync(USER_INFO);
          if (!customerInfo && !userInfo) {
            this.registerType = 'cart';
            this.getUserProfile();
            return false;
          } else if (!customerInfo && !!userInfo) {
            this.registerType = 'cart';
            this.$refs.registerWidgetRef.openJoinMemberModal()
            return false;
          }
          // 获取商品详情
          const goodsInfo = await this.getGoodsDetail(merchantInfo);
          if (!goodsInfo || goodsInfo.code != 1000) return this.handleCartToast({
            success: false,
            msg: "加入购物袋失败"
          });
          // 加入购物车
          const cartRes = await this.$commonFunction.buildProductsAddCart({
            price: goodsInfo.data.skus[0].price,
						itemId: goodsInfo.data.itemId,
            valueId: goodsInfo.data.frontProperties[0].valueId,
            itemCode: goodsInfo.data.itemId,
            itemName: goodsInfo.data.itemName,
            qty: 1,
            skuCode: goodsInfo.data.skus[0].skuCode,
            skuId: goodsInfo.data.skus[0].skuId,
          });
          //  加入购物车提示
          this.handleCartToast(cartRes);
        } catch (e) {
          console.log("###### home-addCart-error", e)
          this.handleCartToast({
            success: false,
            msg: "加入购物袋失败"
          })
        }
      },
      handleScrollTop(e) {
        let tabBarRpx = getApp().globalData.isIpx ? 150 : 120;
        let toPx = this.rpxToPx(tabBarRpx);
        //滚动距离的计算方式为，屏幕的高度-底部tab栏的高度-滚动的距离-顶部nvBar高度
        let toTop = this.systemInfo.screenHeight - e.detail.scrollTop - getApp().globalData.navBarHeight - toPx
        // 将滚动距离从px转换为rpx
        // 这块的110数值是滚动页面console打印的
        if (toTop < 110 && !this.tsTopBannerShow) {
          this.navBarInfo = {
            page: "index",
            logo: "https://100000063-1252208446.file.myqcloud.com/images/macallan-remvp/red-logo.png",
            leftIcon: "https://100000063-1252208446.file.myqcloud.com/images/macallan-remvp/blackSearch.png",
            backgroundColor: "#ffffff"
          }
          this.tsTopBannerShow = true;
        } else if (toTop > 110 && this.tsTopBannerShow) {
          this.navBarInfo = {
            page: "index",
            logo: "https://100000063-1252208446.file.myqcloud.com/images/macallan-remvp/white-logo.png",
            leftIcon: "https://100000063-1252208446.file.myqcloud.com/images/macallan-remvp/search.png",
            backgroundColor: 'transparent',
          }
          this.tsTopBannerShow = false;
        }
        if(this.downArrowShow){
          this.downArrowShow = false;
        }
      },
      //  获取首页utools数据
      async getHomeUtoolsData(option) {
        let json;
        if (option && option.utid) {
          json = await api.getUtoolsJsonP({
            utoolsId: option.utid,
            type: 'home'
          });
        } else {
          json = await api.getUtoolsJson({
            type: 'home'
          });
        }
        if (json && json.success) {
          const _utoolsData = json?.data ? JSON.parse(json.data) : null;
          this.saTrackBanner(_utoolsData);
          //商品
          this.utoolsClassGoodsLists = await this.getCateGoods(_utoolsData?.classId || 8066);
          this.utoolsMetaData = _utoolsData;
          //  数据传入 首页组件
          const _status = await this.getHomeJson(_utoolsData);
          this.showLoaded = false;
        }
      },
      //  抽签购文案修改
      async getBalloutText(){
        try{
          let balloutBannerStatus = getApp().globalData.balloutBannerStatus || false;
          if(balloutBannerStatus) return;
          getApp().globalData.balloutBannerStatus = true;

          let that = this;
          let merchantInfo = uni.getStorageSync(MERCHANT_INFO)
          let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
          if(customerInfo && customerInfo.jwt){
            const recordListResult = await api.recordList({
              header: {
                jwt: customerInfo.jwt
              },
              query: {
                page_no: 1,
                page_size: 100,
              }
            });
            if (recordListResult.code == 1000 && recordListResult.data && recordListResult.data.total) {
              let _listData = recordListResult.data.content;
              let _nowTime = await this.getServerTime();
              let _showBallout = false;
              let systemInfo = uni.getStorageSync(SYSTEM_INFO);
              let isIos = systemInfo.system.indexOf('iOS');
              let _lists = ['恭喜中签','待支付'];
              for(let i=0;i<_listData.length;i++){
                let activityStopTime;
                if (isIos == 0) {
                  activityStopTime = new Date(_listData[i].activityStopTime.replace(/-/g, '/')).getTime() / 1000;
                } else {
                  activityStopTime = new Date(_listData[i].activityStopTime).getTime() / 1000;
                }
                if (activityStopTime > _nowTime && _listData[i].luckyCode && _lists.includes(_listData[i].status)) {
                  _showBallout = true;
                  //  查询商品详情 获取短名
                  const goodsInfo = await this.getGoodsDetail(merchantInfo, _listData[i].itemId);
                  let _name = _listData[i].itemName;
                  if (goodsInfo.code == 1000 && goodsInfo.data && goodsInfo.data.frontProperties && goodsInfo.data.frontProperties[0]){
                    _name = goodsInfo.data.frontProperties[0].subtitle || _listData[i].itemName;
                  }
                  this.cartMessage = `恭喜您中签${_name}购买资格`;
                  this.cartPath = '/pages/customer/recordList';
                  this.cartStatus = false;
                  break;
                }
              }
              //  展示 抽签购中签弹窗
              if(_showBallout){
                this.showCartMsg = true;
                setTimeout(()=>{
                  this.cartMessage = "";
                  this.showCartMsg = false;
                  this.cartPath = "";
                  this.cartStatus = false;
                }, 3000)
              }
            }
          }
        }catch(e){
          console.log("###########getBalloutText-error", e)
        }
      },
      async getServerTime(){
        let nowTime = new Date().getTime() / 1000;
        try{
          const json = await api.getServerTime({
            method: "POST",
            query: {},
          });
          if (json.code === 1000 && json.data) {
            let time = JSON.parse(json.data);
            nowTime = time.server_date / 1000;
          }
          return nowTime;
        }catch(e){
          return nowTime;
        }
      },
      //  查询ts活动吸顶横幅
      async getTsTopBanner() {
        try {
          // utools数据查询
          let json = await api.getUtoolsJson({
            type: 'homepageBanner'
          });
          if (json && json.success) {
            const _tsJson = json?.data ? JSON.parse(json.data) : null;
            if (_tsJson) {
              //  ts数据处理
              if(!this.campaignTargetSaleId) return;
              let tsItems = [];
              _tsJson.children.forEach(element => {
                //  TS数据判断s
                if (element.boxType && element.boxType === 'TS' && element.label1 === String(this.campaignTargetSaleId)) {
                  tsItems.push(element);
                }
              });
              if (tsItems.length) {
                _tsJson.children = tsItems;
                this.tsTopBannerJson = _tsJson;
                return;
              }
            }
          }
          this.tsTopBannerJson = null;
        } catch (e) {
          console.log("####  首页吸顶横幅报错-getTsTopBanner-error",e)
          this.tsTopBannerJson = null;
        }
      },
      /**
       * 神策埋点-首页轮播曝光埋点
       * @param {Object} data
       */
      async saTrackBanner(data) {
        try {
          if (data && data.children && data.children.length) {
            let _trackData = null;
            const _childs = data.children;
            for (let i = 0; i < _childs.length; i++) {
              if (_childs[i].label1 === '首屏swiper' && _childs[i].children.length) {
                const _items = _childs[i].children[0];
                if (_items && !!_items.children && _items.children.length) {
                  const res = _items.children.find(el => el.type === "hotSpace");
                  if (res && res.trackingParams) {
                    _trackData = JSON.parse(res.trackingParams);
                  }
                }
              }
            }
            //  神策埋点-首页banner轮播埋点
            if (_trackData && _trackData.data) {
              this.$commonSensors.lithaTrack.cTrack('BannerExposure', _trackData.data);
            }
          }
        } catch (e) {
          console.log("###### home-saTrackBanner-error:", e)
        }
      },
      /**
       * 查询首页商品分类列表
       * @param {Object} class_id
       * @param {Object} is_sort
       */
      async getCateGoods(class_id, is_sort) {
        const that = this;
        try {
          //获取商品
          let merchantInfo = uni.getStorageSync(MERCHANT_INFO)
          let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
          let res = await this.$commonFunction.doSearchGoods(class_id, '', 1, 200, null, '', is_sort, '', '', '', '',
            true);
          let cateProductList = res.data.content; // 商品列表
          //sku实时库存查询
          let skuCodeList = [],
            goodsQ = [];
          for (let i = 0; i < cateProductList.length; i++) {
            skuCodeList = skuCodeList.concat(cateProductList[i].skuCodes)
          }

          if (skuCodeList.length) {
            skuCodeList = await this.setSkuCodeList(skuCodeList)
            for (let i = 0; i < skuCodeList.length; i++) {
              let reset = await this.getAvailableBatchQty(customerInfo, merchantInfo, skuCodeList[i]);
              goodsQ = reset.length ? goodsQ.concat(reset) : goodsQ
            }
          }
          let list = [];
          cateProductList = cateProductList.map(async item => {
            item.frontQty = 0
            let res = await this.$commonFunction.priceRulesDeal(item.strategies, item.itemmCode)
            if (goodsQ && goodsQ.length) {
              for (let i = 0; i < goodsQ.length; i++) {
                if (item.skuCodes.indexOf(goodsQ[i].skuCode) !== -1 && goodsQ[i].availableQty > 0) {
                  item.frontQty += goodsQ[i].availableQty
                }
              }
            }
            if (res.price !== 0) {
              if (item.itemCode == res.itemCode) {
                item.price = res.price
              }
            }
            if (res.rulesArr.length > 0) {
              if (item.itemCode == res.itemCode) {
                item.rulesArr = res.rulesArr
              }
            }
            // var isForwardpurchaseGoods = false;
            // let  customPromotionTags = item['promotionTagList']?.map(ite=>{
            // 	if (ite.promotionType == 'custom_tag') {
            // 	  customPromotionTags.push(tagItem);
            // 	}

            // 	if (tagItem.promotionType == 'forward_purchase') {
            // 	  isForwardpurchaseGoods = true;
            // 	}
            // 	return ite.promotionType == 'custom_tag'? ite : null
            // })
            list.push(item);
            return item
          })
          return list
        } catch (err) {
          console.log("###### home-getCateGoods-error:", err)
          return null
        }
      },
      async setSkuCodeList(skuCodeList) {
        if (skuCodeList.length < 21) {
          return [skuCodeList]
        } else {
          const result = skuCodeList.flatMap((value, index, array) => {
            if (index % 20 === 0) {
              return [array.slice(index, index + 20)];
            }
            return [];
          });
          return result
        }
      },
      /**
       * 查询有效库存
       * @param {Object} customerInfo
       * @param {Object} merchantInfo
       * @param {Object} skuCodeList
       */
      async getAvailableBatchQty(customerInfo, merchantInfo, skuCodeList) {
        let reset = await api.getAvailableBatchQty({
          method: "POST",
          header: {
            jwt: customerInfo.jwt,
            'content-type': 'application/json'
          },
          query: skuCodeList
          // query: JSON.stringify(skuCodeList)
        }, merchantInfo.cloudMerchantId);
        if (reset.msg == "SUCCESS" && reset?.data?.length) {
          return reset.data.filter(item => item.availableQty > 0)
        } else {
          return []
        }
      },
      onApiList() {
        return api
      },
      registerSuccess: async function() {
        let that = this
        that.showRegister = 1

        // that.$refs.cmsPage.toParseRegisterSuccess()
      },
      async openWelcomeDialog(type) {
        if (type == 'wxparse') {
          await this.refreshTsInfo()
        }
        this.$store.commit('changeWelcomeDialogStatus', true)
      },
      joinVip() {
        let clTrackPrams = {
          'c_pagename': '首页'
        }
        this.registerType = 'nonMember'
        getApp().commonClTrack('c_ebmp_click_join_member', clTrackPrams)
        this.$refs.registerWidgetRef.openJoinMemberModal()
        this.$commonSensors.registerButtonClick('首页按钮')
      },
      //调用入会操作
      onJoinVip(e) {
        this.registerType = 'nonMember'
        this.joinVip()
      },
      refreshTsInfo() {
        // 重新查询用户ts信息
        this.$refs.welcomeRef.getTsByUser()
      },

      async getOrderInfo() {
        let that = this
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO)
        const json = await api.getOrderInfo({
            header: {
              jwt: customerInfo.jwt
            }
          },
          this.submitOrderId
        );
        if (json.code === 1000) {
          if (json.data.status == 'WAIT_SELLER_SEND_GOODS') {
            uni.redirectTo({
              url: '/pages/order/paySuccess?orderNo=' + this.submitOrderId
            });
            this.submitOrderId = ''
          } else {
            // that.showLoaded = false
          }
        } else {
          // that.showLoaded = false
        }
      },

      //付款
      payMoney: async function() {
        let that = this;
        const accountInfo = uni.getAccountInfoSync()
        let {
          orderId,
          orderCode,
          payType
        } = this.partPaymentArr[0]
        //获取item传参埋点
        let currentOrderInfo = this.partPaymentArr[0]
        let itemIdArr = []
        let itemArr = []
        currentOrderInfo.items.forEach(function(item, index) {
          itemIdArr.push(item.itemId)
          itemArr.push({
            itemId: item.itemId,
            itemName: item.itemName,
            price: item.price,
            qty: item.qty,
            remark: currentOrderInfo.buyerRemark,
            skuInfo: {
              itemCapacity: item.skuProperties[0].valueName,
            },
          })
        });
        that.submitOrderId = orderId
        let orderFlow = this.$programSetting.openAppointment;
        let objOrder = this.$commonFunction.isOrderType(currentOrderInfo, orderFlow);
        that.$commonFunction.payMoney(this.partPaymentArr[0], this, objOrder, '首页').then((res) => {
          tip.loaded();
        }).catch((err) => {})

      },
      toOrder() {
        this.payMoney()
      },
      getMyOrder: async function() {
        let that = this;
        let merchantInfo = uni.getStorageSync(MERCHANT_INFO);
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
        const parmas = {
          customer_id: customerInfo.customerId,
          merchant_id: merchantInfo.cloudMerchantId,
          store_id: merchantInfo.cloudMerchantStoreId,
          page_no: 1,
          page_size: 20,
          status: 'BUYER_PART_PAYMENT'
        };
        let json;
        if (uni.getStorageSync("commonEnable")) {
          json = await api.getMyOrderListWithEvaluation({
            header: {
              jwt: customerInfo.jwt
            },
            query: parmas
          });
        } else {
          json = await api.getMyOrderList({
            header: {
              jwt: customerInfo.jwt
            },
            query: parmas
          });
        }
        if (json.data.code === 1000 && !!json.data.data.content && json.data.data.content.length > 0) {
          this.partPaymentArr = json.data.data.content
          this.getIconTime()
        } else {
          this.partPaymentArr = []
        }
      },
      getIconTime() {
        let orderInfo = this.partPaymentArr[0];
        let iconCutTime;
        let systemInfo = uni.getStorageSync(SYSTEM_INFO);
        let isIos = systemInfo.system.indexOf('iOS');
        let cancelTime = getApp().globalData.cancelTime * 60;
        let nowTime = new Date().getTime()
        if (!!orderInfo.planEndTime) {
          if (isIos == 0) {
            iconCutTime = (new Date(orderInfo.planEndTime.replace(/-/g, '/')).getTime() - nowTime)
          } else {
            iconCutTime = (new Date(orderInfo.planEndTime).getTime() - nowTime)
          }
        } else {
          if (!!orderInfo.approveTime) {
            if (isIos == 0) {
              iconCutTime = cancelTime - (nowTime - new Date(orderInfo.approveTime.replace(/-/g, '/'))
                .getTime())
            } else {
              iconCutTime = cancelTime - (nowTime - new Date(orderInfo.approveTime).getTime())
            }
          } else {
            if (isIos == 0) {
              iconCutTime = cancelTime - (nowTime - new Date(orderInfo.createTime.replace(/-/g, '/'))
                .getTime())
            } else {
              iconCutTime = cancelTime - (nowTime - new Date(orderInfo.createTime).getTime())
            }
          }
        }
        if (iconCutTime > 0) {
          setTimeout(() => {
            this.getMyOrder()
          }, iconCutTime);
        } else {
          this.partPaymentArr = []
        }
      },
      handleLoad(val) {
        // this.showLoaded = val
      },
      // 好友助力
      taskInviteHelp() {
        let {
          unionId
        } = uni.getStorageSync(USER_SPECICAL_INFO)
        let {
          shareMemberId,
          taskCenterCode,
          taskContentId,
          taskContentName,
          fromMobile
        } = this.taskParams || uni.getStorageSync('taskParams')
        this.helpValid(shareMemberId, taskCenterCode, taskContentId, unionId)
      },
      //  好友助力校验
      async helpValid(shareMemberId, taskCenterCode, taskContentId, unionId) {
        const res = await api.helpValid({
          method: 'GET',
          header: {},
          query: {
            memberId: shareMemberId,
            taskCenterCode: taskCenterCode,
            taskContentId: taskContentId,
            unionId: unionId
          }
        })
        if (res.code == 1000) {
          this.showTaskHelp = true
          this.taskStatus = 3
          this.$commonSensors.popupEvent('PopupExposure', {
            'popup_type': '抽签任务',
            'popup_name': '助力弹窗'
          })
        } else {
          this.showTaskHelp = false
          if (res.code == -1004) {
            this.showTaskHelp = true
            this.taskStatus = 1
            this.$commonSensors.popupEvent('PopupExposure', {
              'popup_type': '抽签任务',
              'popup_name': '助力已完成弹窗'
            })
          } else {
            this.openWelcomeDialog()
          }
        }
      },
      async doHelp() {
        let {
          unionId
        } = uni.getStorageSync(USER_SPECICAL_INFO)
        let {
          shareMemberId,
          taskCenterCode,
          taskContentId,
          taskContentName,
          fromMobile
        } = this.taskParams || uni.getStorageSync('taskParams')
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO); //助力人信息
        //助力track
        let helpTrackParams = {
          "c_mobile": fromMobile, //被助力人手机号
          "c_drawtask_id": taskContentId,
          "c_drawtask_name": taskContentName
        }
        getApp().commonClTrack("c_ebmp_drawstask_assistance", helpTrackParams);
        const res = await api.helpComfirm({
          method: 'PUT',
          query: {
            memberId: shareMemberId,
            taskCenterCode: taskCenterCode,
            taskContentId: taskContentId,
            unionId: unionId
          }
        })
        if (res.code === 1000) {
          this.trackTaskInvite();
          this.taskStatus = 2
          this.$commonSensors.popupEvent('PopupExposure', {
            'popup_type': '抽签任务',
            'popup_name': '助力成功弹窗'
          })
        } else {
          if (res.code == '-1002') {
            this.handleShowTextToast('本次不凡甄选任务已结束，期待您下次参与')
          }
          this.closeDialog(res.code)
        }
      },

      async trackTaskInvite() {
        let {
          shareMemberId,
          taskCenterCode,
          taskContentId,
          taskContentName,
          fromMobile,
          fromCustomerId
        } = this.taskParams || uni.getStorageSync('taskParams')
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO); //助力人信息
        const res = await api.trackInvite({
          method: 'POST',
          query: {
            merchantId: this.merchantId,
            initiatorMobile: fromMobile, //邀请人手机号
            recipientMobile: customerInfo.mobile, //被邀请人手机号
            taskContentId: taskContentId, //活动ID
            taskContentName: taskContentName, //活动名称
            initiatorCustomerId: fromCustomerId, //邀请人customerId
            recipientCustomerId: customerInfo.customerId //被邀请人customerId
          }
        });
      },

      closeDialog(code) {
        this.showTaskHelp = false
        if (code == '-1002') {
          setTimeout(() => {
            this.openWelcomeDialog()
          }, 2500)
        } else {
          this.openWelcomeDialog()
        }
      },
      /** 18岁弹窗确认 */
      onRegisterWidgetFinish(e) {
        this.finish = true
        const customerInfo = uni.getStorageSync(CUSTOMER_INFO);
        const userInfo = uni.getStorageSync(USER_INFO);
        if (this.sceneType == 'taskHelp') {
          this.taskInviteHelp()
          return
        }
        //
        if (e.componentName == 'register-widget') {
          if (!!uni.getStorageSync('firstEnter')) {
            this.openWelcomeDialog()
          }
        } else if (e.componentName == 'message-modal') {
          setTimeout(async () => {
            await this.refreshTsInfo()
            this.openWelcomeDialog()
          })
        } else {
          if (!!uni.getStorageSync('firstEnter')) {
            this.openWelcomeDialog()
          }
        }

        if (this.registerType == 'cart') {
          if (e.componentName == 'age-check-modal') {
            return
          }
          this.userStatus()
        } else {
          this.getHomeJson(this.utoolsMetaData);
          this.speciallyInviteShow = true;
        }

      },
      onPageScroll(e) {
        let navbarHeight = getApp().globalData.navBarHeight;
        if (e.scrollTop > navbarHeight) {
          this.navbarData.isTopFixed = false;
        } else {
          this.navbarData.isTopFixed = true;
        }
        if (!e.scrollTop) {
          this.isSwiperscaleAnimation = true;
        }
      },
      scrollDown() {
        this.isSwiperscaleAnimation = false;
      },
      async onShareAppMessage(res) {
        if (res.from === 'button') {} else {
          this.$EFSTracking.trackingAction('SHARE_CARD', res.from, {});
        }
        let path = '/pages/home/home'
        this.$commonSensors.sensorsPageShare();
				this.$sr.setContext({ share_title: this.shareTitle });
        return this.$commonFunction.commonShare(res, this.shareTitle, path, this.shareImage)
      },
      onShareTimeline() {
        return {
          title: this.shareTitle,
          query: '',
          imageUrl: this.shareImage
        };
      },
      onUnload(options) {
        // 页面关闭后销毁实例
        if (observer) {
          observer.disconnect()
        }
      },
      //根据商品id获取商品详情
      async getGoodsDetail(merchantInfo, goodsId) {
        const _goods = goodsId || this.goodsId;
        const json = await api.goodsDetail({
            query: {
              merchant_id: merchantInfo.cloudMerchantId,
              store_id: merchantInfo.cloudMerchantStoreId
            }
          },
          _goods
        );
        return json
      },
      //注册成功之后员加入购物车
      async userStatus() {
        // 用户是否登录
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO) || '';
        if (this.registerType == 'cart') {
          this.addCart();
        }
      },

      /**
       * 加购提示
       * @param {Object} obj
       */
      async handleCartToast(obj) {
				const _arr = ['您动作太快，请慢点哟～', '网络状态不佳，请重试'];
				if(obj.msg && _arr.includes(obj.msg)){
					this.handleShowTextToast(obj.msg)
				}else if(obj.data && obj.data.msg && obj.data.type === 'showToast'){
					this.handleShowTextToast(obj.data.msg)
				}else{
					if (obj?.success) this.getCartList();
					this.cartMessage = obj?.msg || "加入购物袋失败";
					this.cartStatus = obj?.success || false;
					this.showCartMsg = true;
					setTimeout(() => {
						this.showCartMsg = false;
					}, 3000);
				}
      },
      //获取购物车商品列表
      getCartList: async function() {
        let that = this;
        let cart_key = uni.getStorageSync(CART_KEY);
        let jwt = uni.getStorageSync(CUSTOMER_INFO).jwt;
        try {
          if (jwt && cart_key !== null) {
            that.$commonFunction.getCartList().then((res) => {
              if (res && res.items !== null) {
                getApp().globalData.cartNum = res.availableTotalQty;
                that.cartNum = res.availableTotalQty;
                that.$store.commit('changeCartNum', res.availableTotalQty);
                uni.setStorageSync('cartNum', res.availableTotalQty);
              }
            }).catch((err) => {
              that.handleShowTextToast(err.msg);
            });
          }
        } catch (err) {
          console.log("#######  home-getCartList-error:", err);
        }
      },
      onAddCart(e) {
        this.goodsId = e.detail.data.itemId;
				this.addCart();
      },
      getUserProfile: async function() {
        let that = this
        this.$commonFunction.commonLoginNew().then(res => {
          if (res.code !== 1000) {
            this.$refs.registerWidgetRef.openJoinMemberModal()
          }else if(res.data && res.data.mobile){
            //  非大陆手机号按照非会员对待,重新入会
            const phoneNumberReg = /^1\d{10}$/;
            if(!phoneNumberReg.test(res.data.mobile)){
              this.$refs.registerWidgetRef.openJoinMemberModal()
            }
          }
        }).catch(err => {
          this.$refs.registerWidgetRef.openJoinMemberModal()
        })
      },
      onChangeNavStatus(e) {
        this.timer = setTimeout(() => {
          if (this.timer) {
            this.timer = null
          } else {
            if (e.detail.data == 1) {
              this.navbarData.isTopFixed = true
            } else {
              this.navbarData.isTopFixed = false
            }
          }
        }, 200)

      },
      setUtoolsP(state) {
        this.utoolsPosition = state
      },
    },
  }
</script>
<style lang="less">
  .hiddenHome {
    opacity: 0;
  }

  .showHome {
    opacity: 1;
  }

  .kaiping .wx-swiper-dots.wx-swiper-dots-horizontal {
    margin-bottom: 10px !important;
  }

  /* 首页 */
  .home {
    // padding-bottom: 110rpx;
    max-width: 750px;
    overflow: hidden;
    z-index: 1;
  }

  .fix-iphonex-home {
    // padding-bottom: 150rpx;
  }

  .containerHome {
    display: none;
  }

  .imgsize_1 {
    width: 750rpx;
    height: 1330rpx;
  }

  .imgsize_1080_600 {
    width: 694rpx;
    height: 694rpx;
  }

  .imgsize_750-1000 {
    width: 694rpx;
    height: 900rpx;
  }

  .imgsize_3 {
    width: 694rpx;
    height: 900rpx;
  }

  .imgsize_4 {
    width: 694rpx;
    height: 1020rpx;
  }

  .imgsize_5 {
    width: 694rpx;
    height: 900rpx;
  }

  .takeover {
    background-color: #666666;
    padding: 244rpx 0;
    text-align: center;
  }

  .takeover .mob_center {
    padding: 0 80rpx;
    text-align: center;
    color: #fff;
  }

  .takeover h2 {
    display: block;
    font-size: 64rpx;
    line-height: 76rpx;
    padding: 40rpx 0;
  }

  .takeover p {
    padding-bottom: 40rpx;
    font-size: 36rpx;
    line-height: 44rpx;
    display: block;
  }

  .takeover .title-card-link {
    margin: 20rpx auto;
    background-color: #ffffff;
    border: 1px solid #ffffff;
    font-size: 26rpx;
    line-height: 42rpx;
    letter-spacing: 0.0825em;
    text-align: center;
    width: 400rpx;
    padding: 24rpx 18rpx 16rpx 18rpx;
  }

  image {
    display: block;
  }

  .flex-box {
    display: flex;
    flex-flow: row no-wrap;
    justify-content: space-around;
    align-items: flex-start;
    line-height: 80rpx;
    /* border: 1px solid red; */
  }

  .flex-item {
    text-align: center;
    flex: 1;
    /* width: 16.66%; */
  }


  //首页滑动
  @keyframes moveSlideshow {
    100% {
      transform: translateX(-186.6666%);
    }
  }

  //首页轮播箭头动画
  @-webkit-keyframes flowUpDown {
    0% {
      bottom: 26rpx;
      opacity: 1;
    }

    50% {
      bottom: 16rpx;
      opacity: 0.1;
    }

    100% {
      bottom: 26rpx;
      opacity: 1;
    }
  }

  @keyframes flowUpDown {
    0% {
      bottom: 26rpx;
      opacity: 1;
    }

    50% {
      bottom: 16rpx;
      opacity: 0.1;
    }

    100% {
      bottom: 26rpx;
      opacity: 1;
    }
  }

  .paty-payment {
    width: calc(100% - 52rpx);
    height: 90rpx;
    margin: 0 auto;
    position: fixed;
    left: 0;
    right: 0;
    top: 10.5%;
    border-radius: 8rpx;
    background-color: #4D4D4D;
    color: #fff;
    display: flex;
    align-items: center;
    padding: 0 30rpx;
    z-index: 1;
    justify-content: space-between;

    text {
      font-size: 28rpx;
    }

    image {
      width: 28rpx;
    }
  }

  .join-vip {
    border-radius: 50%;
    overflow: hidden;
    // background-image: url(https://100000063-1252208446.file.myqcloud.com/images/update/20221130-231920.png);
    background-image: url(https://100000063-1252208446.file.myqcloud.com/images/litha/litha-index/0804/yuan.png);
    background-size: 130rpx 130rpx;
    background-position: center;
    background-repeat: no-repeat;
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    // justify-content: center;

    .mcl-xinxi {
      font-size: 40rpx;
      color: #fff;
      line-height: 72rpx;
    }

    .desc {
      line-height: 18rpx;
      color: #fff;
      font-size: 20rpx;
      margin-top: 13rpx;
    }
  }

  .join-vip {
    z-index: 1008;
    padding: 0;
    background-color: transparent;
    margin-top: 70rpx;
    font-size: 32px;
    position: fixed;
    right: 0rpx;
    bottom: 515rpx;
    width: 108rpx;
    height: 108rpx;
  }

  .guanzhu {
    width: 41rpx;
    height: 38rpx;
    margin-top: 20rpx;
  }

  .ssssitem {
    width: 100%;
    height: 400rpx;
    background-color: red;
  }

  .view-port-box {
    position: fixed;
    left: 0;
    top: 0;
    z-index: 9999;
    width: 750rpx;
    height: 100vh;
    background-color: rgba(256, 128, 128, 0.5);
  }


  .page_box {
    height: 100vh;
    display: flex;
    flex-direction: column;
  }

  .container {
    position: relative;
  }

  .scrollarea {
    flex: 1;
    height: calc(100vh - 220rpx);
    overflow-y: hidden;
    position: relative;
  }

  .scrollisIpx {
    height: calc(100vh - 250rpx);
    position: relative;
  }

  .userinfo {
    display: flex;
    flex-direction: column;
    align-items: center;
    color: #aaa;
    width: 80%;
  }

  .userinfo-avatar {
    overflow: hidden;
    width: 128rpx;
    height: 128rpx;
    margin: 20rpx;
    border-radius: 50%;
  }

  .usermotto {
    margin-top: 200px;
  }

  .avatar-wrapper {
    padding: 0;
    width: 56px !important;
    border-radius: 8px;
    margin-top: 40px;
    margin-bottom: 40px;
  }

  .avatar {
    display: block;
    width: 56px;
    height: 56px;
  }

  .nickname-wrapper {
    display: flex;
    width: 100%;
    padding: 16px;
    box-sizing: border-box;
    border-top: .5px solid rgba(0, 0, 0, 0.1);
    border-bottom: .5px solid rgba(0, 0, 0, 0.1);
    color: black;
  }

  .nickname-label {
    width: 105px;
  }

  .nickname-input {
    flex: 1;
  }

  .down-arrow {
    width: 65rpx;
    height: 65rpx;
    position: absolute;
    /* top: 1338rpx; */
    bottom: 52rpx;
    left: 50%;
    transform: translate(-50%, 0);
    z-index: 2;
  }

  .down-arrow-img {
    width: 65rpx;
    height: 65rpx;
  }

  ::-webkit-scrollbar {
    display: none;
    width: 0;
    height: 0;
    color: transparent;
  }

  .ts_activity_banner {
    position: fixed;
    top: 0;
    left: 0;
    width: 750rpx;
    z-index: 12;
    // transition: all 50ms;
  }
</style>
